package public

import (
	"github.com/dgrijalva/jwt-go"
	"rock/customer/initParam"
	"time"
)

var faeJwtSecret = []byte(initParam.JwtSecretConf.Secret)

type FAEClaims struct {
	UserId   uint32 `json:"userId"`
	Mobile   string `json:"mobile"`
	Password string `json:"password"`
	Name     string `json:"name"`
	jwt.StandardClaims
}

//生成token
func GenerateFAEToken(userId uint32, mobile, password, name string) (string, error) {

	dd := time.Duration(initParam.JwtSecretConf.ExpireTime) * time.Hour

	nowTime := time.Now()
	expireTime := nowTime.Add(dd)

	claims := FAEClaims{
		userId,
		mobile,
		password,
		name,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "gin-blog",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(faeJwtSecret)

	return token, err
}

//解析token
func ParseFAEToken(token string) (*FAEClaims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &FAEClaims{}, func(token *jwt.Token) (interface{}, error) {
		return faeJwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*FAEClaims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
